package com.pc.tas.export;

import com.pc.tas.export.expfilelist.ExpFileList;
import com.pc.tas.export.expfilelist.ExpFileListService;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExportResult{
	
	private ExpFileListService es;
	
	final public static MathContext mctx = new MathContext(4);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	WritableWorkbook wwb = null;
	OutputStream os = null;
	File file = null;
	WritableSheet ws = null;
	String fileName;
	String filePath;
	Map<String,String> fieldMap;
	String sheetName;
	private int j;
	List<String> keys;
	boolean isHasData = false;
	public int expType;
	String httpPath;
	
	public void setPath(HttpServletRequest request) throws Exception{
		filePath = request.getRealPath("/");
		//String path = System.getProperty("java.io.tmpdir");
		//System.out.println("temp dir:" + path);
		httpPath = URLUtil.getUrlHttpPath(request);
		filePath = filePath  + "export/" + fileName;
		httpPath = httpPath + "/export/" + fileName;
		
	}
	
	public void createFile(HttpServletRequest request,String fileName,JSONArray fields) throws Exception{
		j = 0;
		this.getFileName(fileName);
		this.setPath(request);
		this.createFS();
		this.createFields(fields);
	}
	
	private void createFS(){
    	if(sheetName == null || "".equals(sheetName)){
	   		//sheetName = dateFormat.format(new Date());
    		sheetName = "数据";
	   	}
		
		file = new File(filePath);
		try {
            os = new FileOutputStream(file);
            wwb = Workbook.createWorkbook(os);
            ws = wwb.createSheet(sheetName, 0);
            addExpFileList();
       } catch (FileNotFoundException e) {
       		System.out.println("Error:File Path perhaps is not right");
            e.printStackTrace();
       }catch(IOException e){
    	   e.printStackTrace();
       }
	}
	
	private void createFields(JSONArray fields) throws Exception{
		keys = new ArrayList<String>();
		int l = 0;
		for(int i =0; i < fields.length(); i ++){
			JSONObject field = fields.getJSONObject(i);
			Iterator<String> it = field.keys();
			if(it.hasNext()){
				String key = it.next();
				String value = field.getString(key);
				keys.add(key);
				ws.addCell(new Label(l++, 0, value));
			}
			
		}
	}
	
	public void doExport(JSONArray result){
		 
        try {
        	
	        for(int i = 0; i < result.length(); i ++){
	        	isHasData = true;
	        	JSONObject jo = result.getJSONObject(i);
	        	int cell = 0;
	        	j++;
	        	for(String key : keys){
	        		String value = null;
	        		try{
	        			value = String.valueOf(jo.get(key));
	        		}catch(Exception e){
	        		}
	        		
	        		int c = cell ++;
	        		try{
	        			ws.addCell(new Number(c, j, Double.parseDouble(value)));
	        		}catch(Exception e){
	        			ws.addCell(new Label(c, j, value == null ? "" : value));
	        		}
	        		/*if(key.equals("name")){
	        			ws.addCell(new Label(cell++, j, String.valueOf(jo.get(key)) == null ? "" : String.valueOf(jo.get(key))));
	        		}else{
	        			try{
	        				ws.addCell(new Number(cell++, j, Double.parseDouble(String.valueOf(jo.get(key)))));
	        			}catch(Exception e){
	        				ws.addCell(new Number(cell++, j, 0));
	        			}
	        		}*/
	        	}
	        	
			    String process = null;
			    try{
			    	if(result.length() != 0){
				    	process = (new BigDecimal(j).divide(new BigDecimal(result.length()),mctx)).multiply(new BigDecimal(100)).setScale(2, 1) + "%";
				    }
			    }catch(Exception e){
			    	process ="";
			    }
	        }
		} catch (Exception ex) {
		    ex.printStackTrace();
		}
	}
	
	private String getFileName(String fName){
		String timeString = dateFormat.format(new Date());
		if(fName == null || "".equals(fName)){
			fName = timeString;
		}
		fileName = fName + ".xls";
		return fileName;
	}
	
	private void addExpFileList() {
		ExpFileList efl = new ExpFileList();
		efl.setFileName(fileName);
		efl.setFileAddress(httpPath);
		efl.setExpType(expType);
		efl.setOperatingTime(new Timestamp(System.currentTimeMillis()));
		es.insert(efl);
	}
	
	
	public void close() throws Exception {
		wwb.write();
		if (wwb != null)
			wwb.close();
		if (os != null)
			os.close();
	}
	
	public boolean isHasData() {
		return isHasData;
	}

	public void setHasData(boolean isHasData) {
		this.isHasData = isHasData;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public int getExpType() {
		return expType;
	}

	public void setExpType(int expType) {
		this.expType = expType;
	}
	
	public void setEs(ExpFileListService es) {
		this.es = es;
	}

}
